package cn.shiro.shiroservice.common.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.Driver;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.sql.SQLException;


/**
 * &#064;Time 2024 一月 星期三 22:37
 *
 * @author ShangGuan
 */
@org.springframework.context.annotation.Configuration
public class SqlSessionUtils {

    private static String url = "jdbc:mysql://localhost:3306/shiro_service_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
    private static String username = "root";
    private static String password = "12345678";

    public static <T> T getSqlMapper(Class<T> clazz)  {
        return getSqlMapper(clazz,username,password,url);
    }

    public static <T> T getSqlMapper(Class<T> clazz,String username,String password,String url)  {
        DruidDataSource druidDataSource = new DruidDataSource();
        try {
            druidDataSource.setDriver(new Driver());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return getSqlMapper(druidDataSource,clazz);
    }

    /**
     * 获取sql会话
     *
     * @param druidDataSource 德鲁伊数据源
     * @param clazz           拍手
     * @return {@link T}
     */

    public static <T> T getSqlMapper(DruidDataSource druidDataSource,Class<T> clazz)  {
        SqlSession sqlSession = getSqlSession(druidDataSource, clazz);
        return sqlSession.getMapper(clazz);
    }

    public static <T> SqlSession getSqlSession(DruidDataSource dataSource,Class<T> clazz)  {
        Environment environment = new Environment("development", new JdbcTransactionFactory(), dataSource);
        Configuration configuration = new Configuration();
        configuration.addMapper(clazz);
        configuration.setEnvironment(environment);
        return getSqlSession(configuration);
    }

    private static SqlSession getSqlSession(Configuration configuration){
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        return sqlSessionFactory.openSession();
    }



}
